package handler

import (
	"context"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
	"mxshop_srvs/userop_srv/global"
	"mxshop_srvs/userop_srv/model"
	"mxshop_srvs/userop_srv/proto"
)

func (*UserOp) MessageList(ctx context.Context, req *proto.MessageRequest) (*proto.MessageListResponse, error) {

	var messageListResponse proto.MessageListResponse
	var messageList []model.LeavingMessages

	var whereMap map[string]interface{}
	if req.MessageType != 0 {
		whereMap["message_type"] = req.MessageType
	}
	if req.UserId != 0 {
		whereMap["user"] = req.UserId
	}
	if req.Subject != "" {
		whereMap["subject"] = req.Subject
	}

	if result := global.DB.Model(model.LeavingMessages{}).Where(whereMap).Find(&messageList); result.RowsAffected == 0 {
		return nil, status.Error(codes.NotFound, "没有消息")
	} else {
		messageListResponse.Total = int32(result.RowsAffected)
	}

	for _, message := range messageList {
		messageResponse := proto.MessageResponse{
			Id:          message.ID,
			UserId:      message.User,
			MessageType: message.MessageType,
			Subject:     message.Subject,
			Message:     message.Message,
			File:        message.File,
		}
		messageListResponse.Data = append(messageListResponse.Data, &messageResponse)
	}

	return &messageListResponse, nil
}
func (*UserOp) CreateMessage(ctx context.Context, req *proto.MessageRequest) (*proto.MessageResponse, error) {
	return nil, status.Errorf(codes.Unimplemented, "method CreateMessage not implemented")
}
